<?php

function connect_db2($database, $host, $user, $pass)
{
	//echo "db: ".$database." host: ".$host." user".$user." pass".$pass;
	global $connection2;
	$con = 'mysql_pconnect';
	if(!function_exists($con)) {
		throw new RuntimeException("PHP database module missing "
			   . "(no such function: '$con')");
	}

	$connection2 = @$con($host, $user, $pass);

	if(!$connection2) {
		throw new RuntimeException("Could not connect to database server "
			   . "(host=$host,user=$user,password="
			   . str_repeat('*', strlen($pass)) . ")");
	}

	if(!mysql_select_db($database, $connection2)) {
		throw new RuntimeException("Could not select database '"
			   . $database . "': " . mysql_error($connection2));
	}
}

function setup_database_connection_db2($privlevel)
{
	global $connection2, $db;
	//$credfile = ETCDIR . '/dbpasswords.secret';
	$credfile = ETCDIR . '/dbpasswords_db2.secret';
	$credentials = @file($credfile);

	if (!$credentials) {
		user_error("Cannot read database credentials file " . $credfile,
			E_USER_ERROR);
		exit();
	}

	foreach ($credentials as $credential) {
		if ( $credential{0} == '#' ) continue;
		list ($priv, $host, $db, $user, $pass) =
			explode(':', trim($credential));
		if ($priv != $privlevel) continue;

		//$conexion = connect_db2($db."2", $host, $user."w", $pass);	
		//$db2 = $db;
		//$db2 = "domjudge2";
		//connect_db2($db2 , $host, $user."w", $pass);		
		//echo $db2;
	//	echo "db: ".$database." host: ".$host." user".$user." pass".$pass;
		connect_db2($db , $host, $user, $pass);
		
		break;
	}

	if (!$connection2) {
		user_error(sprintf("Privilege level '%s' not supported",
			$privlevel), E_USER_ERROR);
		//exit();
	}
	
	return $connection2;
}

?>
